package com.edu.ahm.juc;

import java.util.concurrent.locks.ReentrantLock;

/*
*  1. 先 定义一个可重入锁 private final ReentrantLock lock = new ReentrantLock();
* 2. lock.lock  lock.unlokc
* */
public class TestLock {
    public static void main(String[] args) {
        TestLock2 testLock2 = new TestLock2();
        new Thread(testLock2,"lock1").start();
        new Thread(testLock2,"lock2").start();
    }
}

class TestLock2 implements Runnable{
     private int ticketNums=10;

     // 定义 lock 锁
    private final ReentrantLock lock = new ReentrantLock();
    @Override
    public  void run() {
        while (true){
            try {
                lock.lock();
                if (ticketNums>0){
                    System.out.println(Thread.currentThread().getName()+"获得了第"+ticketNums--+"票");
                }else {
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }

        }
    }
}
